<?php
//二维码
if ($_REQUEST['arg1'] == 'qrcode') {
    error_reporting(E_ERROR);
    require_once 'includes/wxpay/example/phpqrcode/phpqrcode.php';
    $url = urldecode($_GET["data"]);
    header("Content-type: image/png");
    QRcode::png($url, false, 0, 8, 0);
    die();
}

$request = explode("?", $_SERVER['REQUEST_URI'], 2);
if (preg_match('/[A-Z]/', $request[0])) {
    $request[0] = strtolower($request[0]);
    $lowercase_file_url = ((($_SERVER['SERVER_PORT'] == 443 || !empty($_SERVER['HTTPS']))?"https://":"http://") . $GLOBALS['HTTP_HOST'] . implode("?", $request));
    header("HTTP/1.1 301 Moved Permanently");
    header("Location: $lowercase_file_url");
    exit();
}
/*
 * header("Pragma: no-cache"); header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
 */
include "includes/functions/functions.php";
global $CONFIG,$SMARTY,$DBobject,$Cardclient;

$SMARTY->loadFilter('output', 'trimwhitespace');

// ASSIGN ALL STORED SMARTY VALUES
foreach ($_SESSION['smarty'] as $key => $val) {
    $SMARTY->assign($key, $val);
}
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$SMARTY->assign('DOMAIN', $protocol. $GLOBALS['HTTP_HOST']);
unset($_SESSION['smarty']);
$SMARTY->assign('error', $_SESSION['error']);
unset($_SESSION['error']); // ASSIGN ERROR MESSAGES FOR TEMPLATES
$SMARTY->assign('notice', $_SESSION['notice']);
unset($_SESSION['notice']); // ASSIGN NOTICE MESSAGES FOR TEMPLATES
$SMARTY->assign('post', $_SESSION['post']);
unset($_SESSION['post']); // ASSIGN POST FOR FORM VARIABLES
$SMARTY->assign('address', $_SESSION['address']); // ASSIGN ADDRESS FOR FORM VARIABLES
$SMARTY->assign('students', $_SESSION['students']); // ASSIGN STUDENTS FOR FORM VARIABLES
$SMARTY->assign('comments', $_SESSION['comments']); // ASSIGN COMMENTS FOR FORM VARIABLES
$SMARTY->assign('agreed_tc', $_SESSION['agreed_tc']); // ASSIGN COMMENTS FOR FORM VARIABLES
$SMARTY->assign('preSelected', $_SESSION['preSelected']);
$SMARTY->assign('postcode', $_SESSION['postcode']);
$SMARTY->assign('search', $_SESSION['search']);
$SMARTY->assign('checkoutstep', $_SESSION['checkoutstep']);
$SMARTY->assign('redirect', !empty($_SESSION['redirect'])?$_SESSION['redirect']:(!empty($_SESSION['post']['redirect'])?$_SESSION['post']['redirect']:$_SERVER['HTTP_REFERER']));
unset($_SESSION['redirect']); // ASSIGN REDIRECT URL VALUE AFTER LOGIN AND SHOW LOGIN MODAL
$SMARTY->assign('user', $_SESSION['user']['public']); // ASSIGN USER FOR TEMPLATES
$SMARTY->assign('HTTP_REFERER', rtrim($_SERVER['HTTP_REFERER'], '/'));
$_URI = explode("?", $_SERVER['REQUEST_URI']);
$SMARTY->assign('REQUEST_URI', rtrim($_URI[0], '/'));
$_request = htmlclean($_REQUEST);
$SMARTY->assign('request', $_request);
$SMARTY->assign('orderNumber', $_SESSION['orderNumber']);
$SMARTY->assign('bankTransfer', $_SESSION['bankTransfer']);
$SMARTY->assign('ga_ec', $_SESSION['ga_ec']);// ASSIGN JS-SCRIPTS TO GOOGLE ANALYTICS - ECOMMERCE (USED ON THANK YOU PAGE)
unset($_SESSION ['ga_ec']);

$SMARTY->assign("localIP", $_SERVER['REMOTE_ADDR']);

$token = getToken('frontend');
$SMARTY->assign('token', $token);
$SMARTY->assign('ch_weekday', ['Sunday'=>'星期日', 'Monday'=>'星期一', 'Tuesday'=>'星期二', 'Wednesday'=>'星期三', 'Thursday'=>'星期四', 'Friday'=>'星期五', 'Saturday'=>'星期六']);

//载入语言包
$lang_default = $_SESSION['lang']?:$CONFIG->lang->default;
$lang_dir = $CONFIG->lang->dir.DIRECTORY_SEPARATOR.$lang_default;
$lang = [];
if (is_dir($lang_dir)) {
    $files = scandir($lang_dir);
    array_shift($files);
    array_shift($files);
    foreach ($files as $key => $value) {
        $ls = include_once($lang_dir.DIRECTORY_SEPARATOR.$value);
        $lname = rtrim($value, '.php');
        foreach ($ls as $k => $v) {
            $lang[$lname][$k] = $v;
        }
    }
}
$SMARTY->assign('lang', $lang);
while (true) {
  /******* Processes *******/
    $needle = str_replace("/", "\/", "process/");
    $haystack = $_request["arg1"];
    if (preg_match("/^{$needle}/", $haystack)) {
        foreach ($CONFIG->process as $sp) {
            if ($sp->url == $_request['arg1']) {
                $file = (string)$sp->file;
                include($file);
            }
        }
        die();
    }
  /******* Goes to 404 *******/
    if ($_request['arg1'] == '404') {
        $template = loadPage($CONFIG->error404);
        break 1;
    }
  /******* Goes to 403 *******/
    if ($_request['arg1'] == '403') {
        $template = loadPage($CONFIG->error403);
        break 1;
    }
  /******* Goes to 503 *******/
    if ($_request['arg1'] == '503') {
        $template = loadPage($CONFIG->error503);
        break 1;
    }
  
  /******* Goes to home *******/
    if ($_request['arg1'] == '') {
        $template = loadPage($CONFIG->index_page);
        break 1;
    }
  
  /******* Goes to home *******/
    if ($_request['arg1'] == 'resetpassword') {
        $SMARTY->assign('noindex', true);
        $template = loadPage($CONFIG->resetpassword);
        break 1;
    }
  
  /**
   * ***** Goes to Login ******
   */
    foreach ($CONFIG->login as $lp) {
        if (empty($lp->url)) {
            continue;
        }
        $haystack = str_replace("/", "\/", $lp->url);
        $needle = $_request["arg1"];
        if (preg_match("/^{$needle}/", $haystack)) {
            if (!empty($_SESSION['user']['public']['id'])) {
                header("Location: /" . $lp->fallback_redirect);
                exit();
            }
            $template = loadPage($lp);
            break 2;
        }
    }
  
    /**
     * **** Goes to my-account ******
     */
    if ($_request['arg1'] == 'my-account') {
        if ($CONFIG->account->attributes()->restricted == 'true' && empty($_SESSION['user']['public']['id'])) {
            $_SESSION['redirect'] = "/my-account";
            header("Location: /" . $CONFIG->account->fallback_redirect);
            exit();
        }
        $template = loadPage($CONFIG->account);
        $cart_obj = new Enrolment();
        $payments = $cart_obj->GetOrderHistoryByUser($_SESSION['user']['public']['id']);
        //var_dump($payments);exit;
        $SMARTY->assign('payments', $payments);
        $member_obj = new Member();
    
        $classterm_obj = new ClassTermClass();
        $addressArr = $member_obj->GetUsersAddresses($_SESSION['user']['public']['id']);
        //var_dump($addressArr);exit;
        $currentTerms = $classterm_obj->GetCurrentTerm(0, '', $addressArr[0]['address_state'].','.$addressArr[0]['address_suburb'].','.$addressArr[0]['address_country']);
        //var_dump($currentTerms);exit;
        $SMARTY->assign('currentTerms', $currentTerms);
        if (count($currentTerms)>1) {
            $newTerm = end($currentTerms);
            $newTermUrl = $newTerm['term_url'];
            $newTermclasses = array();
            foreach ($newTerm['classes'] as $c) {
                $newTermclasses[] = $c['class_object_id'];
            }
            $SMARTY->assign('newTermclasses', $newTermclasses);
            $SMARTY->assign('newTermUrl', $newTermUrl);
        }
        $students = $member_obj->GetStudentsByUserId($_SESSION['user']['public']['id']);
        foreach ($students as $student) {
            $studentArr["{$student['student_id']}"] = $student;
            foreach ($currentTerms as $term) {
                $studentArr["{$student['student_id']}"]['curTerm_enrolments'][] = $cart_obj->GetStudentEnrolments($student['student_id'], '', true, $term['term_object_id']);
            }
        }
        //var_dump($studentArr);exit;
        $SMARTY->assign('students', $studentArr);
        break 1;
    }
  
  /**
   * ***** Goes to search ******
   */
    if ($_request['arg1'] == 'search') {
        $template = loadPage($CONFIG->search);
        searchcms($_GET['q']);
        break 1;
    }
  
  /**
   * ***** Goes to CHECKOUT ******
   */
    if ($_request['arg1'] == 'checkout') {
        if (empty($_SESSION['user']['public']['id'])) {
            $_SESSION['redirect'] = "/checkout";
            header("Location: /login-register");
            exit();
        }
        $template = loadPage($CONFIG->checkout);
        $cart_obj = new Enrolment();
        if ($cart_obj->NumberOfProductsOnCart() < 1) {
              header("Location: /");
              exit();
        }
        //$ship_obj = new ShippingClass();
        //$methods = $ship_obj->getShippingMethods($cart_obj->NumberOfProductsOnCart());
        //$SMARTY->assign ( 'shippingMethods', $methods );
        $validation = $cart_obj->ValidateCart();
        $SMARTY->assign('validation', $validation);
        $totals = $cart_obj->CalculateTotal($_SESSION['students']);
        $SMARTY->assign('totals', $totals);

        $sql = "SELECT region_name AS value,region_id AS id FROM tbl_region WHERE region_id mod 10000 = 0 ORDER BY region_id";
        $states = $DBobject->wrappedSql($sql);
        $SMARTY->assign('options_state', $states);
        $SMARTY->assign('options_suburb', $suburbs);
        break 1;
    }
  
    /**
     * ***** Goes to SHOPPING CART ******
     */
    if ($_request['arg1'] == 'shopping-cart') {
        $template = loadPage($CONFIG->cart);
        $cart_obj = new Enrolment();
        //$ship_obj = new ShippingClass();
        //$methods = $ship_obj->getShippingMethods($cart_obj->NumberOfProductsOnCart());
        //$SMARTY->assign ( 'shippingMethods', $methods );
        if (!empty($_SESSION['reApplydiscount']) && !empty($_SESSION['user']['public']['id'])) {
            //RE-APPLY DISCOUNT CODE
            $res = $cart_obj->ApplyDiscountCode($_SESSION['reApplydiscount']);
            if ($res['error']) {
                $_SESSION['error']= $res['error'];
                $_SESSION['post']= $_POST;
            }
            $_SESSION['reApplydiscount'] = '';
            unset($_SESSION['reApplydiscount']);
            header('Location: /shopping-cart');
            die();
        }
        $validation = $cart_obj->validateCart();
        $SMARTY->assign('validation', $validation);
        $totals = $cart_obj->CalculateTotal($_SESSION['students']);
        $SMARTY->assign('totals', $totals);
        break 1;
    }

    /**
     * 支付页面
     */
    if ($_request['arg1'] == 'payment') {
        $pmethod = $_request['pmethod'];
        if (empty($_SESSION['user']['public']['id'])) {
            $_SESSION['redirect'] = "/payment";
            header("Location: /" . $CONFIG->payment->fallback_redirect);
            exit();
        }
        $template = loadPage($CONFIG->payment);

        $orderNumber = $_GET['orderno']?:$_SESSION['orderNumber'];
        $cart_obj = new Enrolment();
        $payment = $cart_obj->getOrderPayment($_SESSION['user']['public']['id'], $orderNumber);
        //var_dump($order);exit;
        $SMARTY->assign('payment', $payment);
        $url = null;
        $trade_no = null;
        if ($payment && $pmethod=='wx') {
            require_once "includes/wxpay/example/WxPay.NativePay.php";
            $notify = new NativePay();
            $input = new WxPayUnifiedOrder();
            $input->SetBody("澳睿跑订单支付-订单:".$payment['payment_transaction_no']);
            //$input->SetDetail("商品详情");
            $input->SetAttach("附加信息");
            list($order_id,$order_time) = explode('-', $payment['payment_transaction_no']);
            $trade_no = WxPayConfig::MCHID.str_pad($order_id, 10, "0", STR_PAD_LEFT).$order_time;
            //$input->SetOut_trade_no(WxPayConfig::MCHID.date("YmdHis"));
            $input->SetOut_trade_no($trade_no);
            $input->SetTotal_fee($payment['payment_total']*100); //标价金额
            $input->SetTime_start(date("YmdHis"));
            $input->SetTime_expire(date("YmdHis", time() + 600));
            $input->SetNotify_url("http://".$_SERVER['SERVER_NAME']."/notify");
            $input->SetTrade_type("NATIVE");
            $input->SetProduct_id($payment['payment_transaction_no']);//商品ID，订单号
            $result = $notify->GetPayUrl($input);
            $url = $result["code_url"];
            //$trade_no = $input->GetOut_trade_no();
            $cart_obj->updateOrderPayment($_SESSION['user']['public']['id'], $orderNumber, ['payment_response_summary_code'=>$trade_no]);
        } else if ($payment && $pmethod=='al') {
            require_once 'includes/alipay/f2fpay/service/AlipayTradeService.php';
            require_once 'includes/alipay/f2fpay/model/builder/AlipayTradePrecreateContentBuilder.php';
            require 'includes/alipay/config.php';
            list($order_id,$order_time) = explode('-', $payment['payment_transaction_no']);
            //订单号
            $trade_no=$config['app_id'].str_pad($order_id, 10, "0", STR_PAD_LEFT).$order_time;
            if (!empty($trade_no)&& trim($trade_no)!=""){
                //商户订单号，商户网站订单系统中唯一订单号，必填
                $out_trade_no = $trade_no;

                //订单名称，必填
                $subject = "澳睿跑订单支付-订单:".$payment['payment_transaction_no'];

                //付款金额，必填
                $total_amount = 0.01;

                //商品描述，可空
                $body = '';

                //超时时间
                $timeout_express="5m";

//                // 商品明细列表，需填写购买商品详细信息，
//                $goodsDetailList = array();
//
//                // 创建一个商品信息，参数含义分别为商品id（使用国标）、名称、单价（单位为分）、数量，如果需要添加商品类别，详见GoodsDetail
//                $goods1 = new GoodsDetail();
//                $goods1->setGoodsId("apple-01");
//                $goods1->setGoodsName("iphone");
//                $goods1->setPrice(3000);
//                $goods1->setQuantity(1);
//                //得到商品1明细数组
//                $goods1Arr = $goods1->getGoodsDetail();
//
//                // 继续创建并添加第一条商品信息，用户购买的产品为“xx牙刷”，单价为5.05元，购买了两件
//                $goods2 = new GoodsDetail();
//                $goods2->setGoodsId("apple-02");
//                $goods2->setGoodsName("ipad");
//                $goods2->setPrice(1000);
//                $goods2->setQuantity(1);
//                //得到商品1明细数组
//                $goods2Arr = $goods2->getGoodsDetail();
//
//                $goodsDetailList = array($goods1Arr,$goods2Arr);

                // 创建请求builder，设置请求参数
                $qrPayRequestBuilder = new AlipayTradePrecreateContentBuilder();
                $qrPayRequestBuilder->setOutTradeNo($out_trade_no);
                $qrPayRequestBuilder->setTotalAmount($total_amount);
                $qrPayRequestBuilder->setTimeExpress($timeout_express);
                $qrPayRequestBuilder->setSubject($subject);
                $qrPayRequestBuilder->setBody($body);

                // 调用qrPay方法获取当面付应答
                $qrPay = new AlipayTradeService($config);
                $qrPayResult = $qrPay->qrPay($qrPayRequestBuilder);

                // 根据状态值进行业务处理
                switch ($qrPayResult->getTradeStatus()){
                    case "SUCCESS":
//                        echo "支付宝创建订单二维码成功:"."<br>---------------------------------------<br>";
                        $response = $qrPayResult->getResponse();
                        $url = $qrPay->create_erweima($response->qr_code);
                        //保存订单号
                        $cart_obj->updateOrderPayment($_SESSION['user']['public']['id'], $orderNumber, ['payment_response_summary_code'=>$trade_no]);
                        break;
                    case "FAILED":
                        echo "支付宝创建订单二维码失败!!!"."<br>--------------------------<br>";
                        if(!empty($qrPayResult->getResponse())){
                            print_r($qrPayResult->getResponse());
                        }
                        break;
                    case "UNKNOWN":
                        echo "系统异常，状态未知!!!"."<br>--------------------------<br>";
                        if(!empty($qrPayResult->getResponse())){
                            print_r($qrPayResult->getResponse());
                        }
                        break;
                    default:
                        echo "不支持的返回状态，创建订单二维码返回异常!!!";
                        break;
                }
            }
        } else if ($payment && $pmethod=='un') {
            include_once 'includes/unionpay/uniopnPayIndex.php';

            list($order_id,$order_time) = explode('-', $payment['payment_transaction_no']);
            $params['orderId'] = $params['merId'].str_pad($order_id, 10, "0", STR_PAD_LEFT).$order_time;  //商户订单号，8-32位数字字母，不能含“-”或“_”
            $params['txnAmt'] = $payment['payment_total']*100;   //交易金额，单位分

            com\unionpay\acp\sdk\AcpService::sign ( $params );
            $uri = com\unionpay\acp\sdk\SDKConfig::getSDKConfig()->frontTransUrl;
            $html_form = com\unionpay\acp\sdk\AcpService::createAutoFormHtml( $params, $uri );
            //保存订单号
            $cart_obj->updateOrderPayment($_SESSION['user']['public']['id'], $orderNumber, ['payment_response_summary_code'=>$params['orderId']]);
            $_SESSION['orderNumber'] = $orderNumber;
            echo $html_form;
        }
        $_SESSION['orderNumber'] = $orderNumber;
        if(isset($url)&&!empty($url)){
            $SMARTY->assign('url', urlencode($url));
        }
        $SMARTY->assign('tradeno', $trade_no);
        $SMARTY->assign('pmethod', $pmethod);
        break 1;
        die();
    }

    /**
     * 微信支付回调页面
     */
    if ($_request['arg1'] == 'notify') {
        require_once "includes/wxpay/example/WxPay.NotifyPay.php";
        //初始化日志
        $file_path = __DIR__. '/logs';
        if (!is_dir($file_path)) {
            if (!mkdir($file_path, 0777, true)) {
                die('Failed to create folders...');
            }
        }
        $logHandler= new CLogFileHandler($file_path.DIRECTORY_SEPARATOR.date('Y-m-d').'.log');
        $log = Log::Init($logHandler, 15);

        Log::DEBUG("begin notify");
        $notify = new PayNotifyCallBack();
        $res = $notify->Handle(false);
        die();
    }

    /**
     * 支付宝支付回调页面
     */
    if ($_request['arg1'] == 'alnotify') {
        require_once 'includes/alipay/f2fpay/service/AlipayTradeService.php';
        require 'includes/alipay/config.php';
        $arr=$_POST;
        /* 实际验证过程建议商户添加以下校验。
        1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
        2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
        3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
        4、验证app_id是否为该商户本身。
        */
        if(!empty($arr['trade_status']) && $arr['trade_status'] == "TRADE_SUCCESS") {//验证成功
            //商户订单号
            $out_trade_no = htmlspecialchars($arr['out_trade_no']);
            //查询订单
//            $queryResponse = new AlipayTradeService($config);
//            $queryResult = $queryResponse->queryTradeResult($out_trade_no);
//            switch ($queryResult->getTradeStatus()){
//                case "SUCCESS":
                    //更新付款信息和课程信息
                    $cart_obj = new Enrolment();
                    $payment = $cart_obj->changPaySuccess('alipay', $out_trade_no);
                    die();
//                    break;
//            }

        }
    }

    /**
     * 银联支付回调页面
     */
    if ($_request['arg1'] == 'unnotify') {
        $params=$_POST;
        if(!empty($params['orderId'])) {//验证成功
            //商户订单号
            $out_trade_no = htmlspecialchars($params['orderId']);
            //更新付款信息和课程信息
            $cart_obj = new Enrolment();
            $cart_obj->changPaySuccess('unipay', $out_trade_no);
            $orderNo = $_SESSION['orderNumber'];
            header("location: /checkout-completed");
            die();
        }
    }

    /**
     * **** Goes to individual script pages ******
     */
    foreach ($CONFIG->static_page as $sp) {
        if ($sp->url == $_request['arg1']) {
            $template = loadPage($sp);
            break 2;
        }
    }
  
  /**
   * ***** ClassTerm pages here ******
   */
    foreach ($CONFIG->classterm as $lp) {
        if (empty($lp->url)) {
            continue;
        }
        $needle = str_replace("/", "\/", $lp->url);
        $haystack = $_request["arg1"];
        if (preg_match("/^{$needle}/", $haystack)) {
            $_nurl = $_request["arg1"];
            $class = (string)$lp->file;
            $obj = new $class($_nurl,$lp);
            $template = $obj->Load();
            $menu = $obj->LoadMenu($lp->pageID);
            $SMARTY->assign('menuitems', $menu);
            foreach ($lp->process as $sp) {
              //if($_SERVER['REMOTE_ADDR']=='150.101.230.130'){die("@");}
                $file = (string)$sp->file;
                if (file_exists($file)) {
                    include($file);
                }
            }
            break 2;
        }
    }
  
  /**
   * ***** Product pages here ******
   */
    foreach ($CONFIG->product_page as $lp) {
        if (empty($lp->url)) {
            continue;
        }
        $needle = str_replace("/", "\/", $lp->url);
        $haystack = $_request["arg1"];
        if (preg_match("/^{$needle}/", $haystack)) {
            $_nurl = $_request["arg1"];
            $class = (string)$lp->file;
            $obj = new $class($_nurl,$lp);
            $template = $obj->Load(null, $_PUBLISHED);
            $obj->LoadAssociatedProducts();
            $menu = $obj->LoadMenu($lp->pageID);
            $SMARTY->assign('menuitems', $menu);
            if ($template == 'product.tpl') {
                $cart_obj = new Enrolment();
                $listingParent = $SMARTY->getTemplateVars('listing_parent');
                $SMARTY->assign('product_FullCategoryName', $cart_obj->getFullCategoryName($listingParent['listing_id']));
            }
            foreach ($lp->process as $sp) {
                $file = (string)$sp->file;
                if (file_exists($file)) {
                    include($file);
                }
            }
            break 2;
        }
    }
  
  /**
   * ***** Listing pages here ******
   */
    foreach ($CONFIG->listing_page as $lp) {
        if (empty($lp->url)) {
            continue;
        }
        $needle = str_replace("/", "\/", $lp->url);
        $haystack = $_request["arg1"];
        if (preg_match("/^{$needle}/", $haystack)) {
            $_nurl = $_request["arg1"];
            $class = (string)$lp->file;
            $obj = new $class($_nurl,$lp);
            $template = $obj->Load(null, $_PUBLISHED);
            $menu = $obj->LoadMenu($lp->pageID);
            $SMARTY->assign('menuitems', $menu);
            foreach ($lp->process as $sp) {
                $file = (string)$sp->file;
                if (file_exists($file)) {
                    include($file);
                }
            }
            break 2;
        }
    }
  /**
   * ***** Dynamic Page Check Here ******
   */
    if (!empty($CONFIG->page_strut)) {
        $struct = $CONFIG->page_strut;
        $class = (string)$struct->file;
        $obj = new $class('',$struct);
        $id = $obj->ChkCache($_request["arg1"], $_PUBLISHED);
        if (! empty($id)) {
            $template = $obj->Load($id, $_PUBLISHED);
            $menu = $obj->LoadMenu($id);
            $SMARTY->assign('menuitems', $menu);
            foreach ($struct->process as $sp) {
                $file = (string)$sp->file;
                if (file_exists($file)) {
                    include($file);
                }
            }
            break 1;
        }
    }
    $template = loadPage($CONFIG->error404);
    break 1;
}

/**
 * ***************************************
 * Load Data Shopping Cart for all pages *
 * ***************************************
 */
$cart_obj = new Enrolment();
$itemNumber = $cart_obj->NumberOfProductsOnCart();
$SMARTY->assign('itemNumber', $itemNumber);
$cart = $cart_obj->GetDataCart();
$SMARTY->assign('cart', $cart);
$subtotal = $cart_obj->GetSubtotal();
$SMARTY->assign('subtotal', $subtotal);
$productsOnCart = $cart_obj->getDataProductsOnCart();
$SMARTY->assign('productsOnCart', $productsOnCart);
$classQtyOnCart = $cart_obj->GetQtyClassOnCart();
$SMARTY->assign('classQtyOnCart', $classQtyOnCart);
if ($CONFIG->checkout->attributes()->guest == 'true') {
    $SMARTY->assign('allowGuest', true);
}

if (empty($template)) {
    $template = loadPage($CONFIG->error404);
}
//var_dump($template);exit;
$page_tpl = "page.tpl";
$SMARTY->display("extends:$page_tpl|$template");
die();


function loadPage($_conf)
{
    global $CONFIG,$_PUBLISHED,$SMARTY;
    if (!empty($_conf->header)) {
         header($_conf->header);
    } else {
        header("HTTP/1.0 200 OK");
    }
    if (strtolower((string)$_conf->attributes()->standalone) == 'true') {
        $template = $_conf->template;
        $SMARTY->display("extends:$template");
        die();
    } else {
        if (!empty($CONFIG->page_strut)) {
            $struct = $CONFIG->page_strut;
            foreach ($_conf->associated as $a) {
                $domdict = dom_import_simplexml($struct->table);
                $domcat  = dom_import_simplexml($a);
                $domcat  = $domdict->ownerDocument->importNode($domcat, true);// Import the <cat> into the dictionary document
                $domdict->appendChild($domcat);// Append the <cat> to <c> in the dictionary
            }
            foreach ($_conf->options as $o) {
                $domdict = dom_import_simplexml($struct->table);
                $domcat  = dom_import_simplexml($o);
                $domcat  = $domdict->ownerDocument->importNode($domcat, true);// Import the <cat> into the dictionary document
                $domdict->appendChild($domcat);// Append the <cat> to <c> in the dictionary
            }
            foreach ($_conf->extends as $e) {
                $domdict = dom_import_simplexml($struct->table);
                $domcat  = dom_import_simplexml($e);
                $domcat  = $domdict->ownerDocument->importNode($domcat, true);// Import the <cat> into the dictionary document
                $domdict->appendChild($domcat);// Append the <cat> to <c> in the dictionary
            }
      
            $class = (string)$struct->file;
            $obj = new $class('',$struct);
            $template = $obj->Load($_conf->pageID, $_PUBLISHED);
            if (!empty($template)) {
                $template = $_conf->template;
                $menu = $obj->LoadMenu($_conf->pageID);
                $SMARTY->assign('menuitems', $menu);
                $SMARTY->assign('requested_page', $_SERVER['HTTP_REFERER']);
            }
        }
    }
    foreach ($_conf->additional as $ad) {
        $tag = (string)$ad->tag;
        $name = (string)$ad->name;
        $data = (string)$ad->data;
        foreach ($CONFIG->$tag as $lp) {
            if ($lp->attributes()->name == $name) {
                $class = (string)$lp->file;
                $obj = new $class('',$lp);
                $data2 = $obj->LoadTree($lp->root_parent_id);
                $SMARTY->assign($data, unclean($data2));
                break 1;
            }
        }
    }
  
    foreach ($_conf->process as $sp) {
        $file = (string)$sp->file;
        if (file_exists($file)) {
            include($file);
        }
    }
 
    return $template;
}
